package com.ruyuan.eshop.data.migrate.tool.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.otter.canal.protocol.CanalEntry;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ruyuan.eshop.data.migrate.tool.mapper.targetdb.TargetOrderAutoNoMapper;
import com.ruyuan.eshop.data.migrate.tool.model.order.OrderAutoNoDO;
import com.ruyuan.eshop.data.migrate.tool.service.TargetOrderAutoNoService;
import com.ruyuan.eshop.data.migrate.tool.util.LoggerFormat;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author zhonghuashishan
 * @version 1.0
 */
@Slf4j
@Service
public class TargetOrderAutoNoServiceImpl implements TargetOrderAutoNoService {

    @Autowired
    private TargetOrderAutoNoMapper targetOrderAutoNoMapper;


    @Override
    public Long getMaxId() {
        return targetOrderAutoNoMapper.getMaxId();
    }

    @Override
    @Transactional(value = "TargetTransactionManager")
    public void consumer(CanalEntry.EventType eventType, JSONObject beforeData, JSONObject afterData) {

        log.info(LoggerFormat.build()
                .remark("consumer->request")
                .data("eventType", eventType)
                .data("beforeData", beforeData)
                .data("afterData", afterData)
                .finish());

        if(CanalEntry.EventType.INSERT.equals(eventType) || CanalEntry.EventType.UPDATE.equals(eventType)) {
            OrderAutoNoDO orderAutoNoDO = afterData.toJavaObject(OrderAutoNoDO.class);

            // 新增或更新记录
            insertOrUpdate(orderAutoNoDO.getId(), orderAutoNoDO);
            return;
        }

        if(CanalEntry.EventType.DELETE.equals(eventType)) {
            OrderAutoNoDO orderAutoNoDO = beforeData.toJavaObject(OrderAutoNoDO.class);

            // 删除记录
            delete(orderAutoNoDO);
        }
    }

    @Override
    @Transactional(value = "TargetTransactionManager")
    public void batchInsert(List<OrderAutoNoDO> orderAutoNoDOList) {

        log.info(LoggerFormat.build()
                .remark("sync->request")
                .data("orderAutoNoDOList", orderAutoNoDOList)
                .finish());

        targetOrderAutoNoMapper.batchInsert(orderAutoNoDOList);
    }

    /**
     * 新增操作 或者 更新操作
     * @param orderAutoNoDO 订单自增ID
     */
    private void insertOrUpdate(Long id, OrderAutoNoDO orderAutoNoDO) {
        // 先验证一下是否存在历史数据
        Date gmtModified = targetOrderAutoNoMapper.getGmtModified(id);
        if(gmtModified == null) {
            // 不存在则执行新增操作
            targetOrderAutoNoMapper.insert(orderAutoNoDO);
            return;
        }

        // 已经存在记录了，比较一下gmtModified
        if(orderAutoNoDO.getGmtModified().after(gmtModified)) {
            // 如果当前的记录比较新，则执行更新操作
            LambdaUpdateWrapper<OrderAutoNoDO> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(OrderAutoNoDO::getId, orderAutoNoDO.getId());
            targetOrderAutoNoMapper.update(orderAutoNoDO, updateWrapper);
        }

        // 否则，丢弃记录不处理
    }

    /**
     * 删除操作
     * @param orderAutoNoDO
     */
    private void delete(OrderAutoNoDO orderAutoNoDO) {
        LambdaQueryWrapper<OrderAutoNoDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderAutoNoDO::getId, orderAutoNoDO.getId());
        targetOrderAutoNoMapper.delete(queryWrapper);
    }

}